<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>添加</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<link rel="stylesheet" href="../../css/oksub.css">
	<link rel="stylesheet" href="../../css/editor/style.css">
	<!-- <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet"/> -->
	<script type="text/javascript" src="../../lib/loading/okLoading.js"></script>
<style>
	#editor—wrapper {
		border: 1px solid #ccc;
		z-index: 100;
		/* 按需定义 */
	}

	#toolbar-container, #toolbar-container-brief {
		border-bottom: 1px solid #ccc;
	}

	#editor-container, #editor-container-brief {
		height: 300px;
	}
</style>

</head>
<body>
<div class="ok-body">
	<!--form表单-->
	<form class="layui-form layui-form-pane ok-form">
		<div class="layui-form-item">
			<div class="layui-col-md6">
				<label class="layui-form-label">上级展项</label>
				<div class="layui-input-block">
					<select name="one_id" id="one_id" lay-filter="one_id" lay-verify="required">
						<option value="">请选择</option>
					</select>
				</div>
			</div>
			<div class="layui-col-md6">
				<label class="layui-form-label">名称</label>
				<div class="layui-input-block">
					<input type="text" name="name" placeholder="请输入名称" autocomplete="off" class="layui-input" lay-verify="required">
				</div>
			</div>
			
		</div>
		<div class="layui-form-item">
			<div class="layui-col-md6">
				<label class="layui-form-label">英文名称</label>
				<div class="layui-input-block">
					<input type="text" name="english_name" placeholder="请输入英文名称" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-col-md6">
				<label class="layui-form-label">排序</label>
				<div class="layui-input-block">
					<input type="text" name="sort" placeholder="排序，数字越小越靠前" autocomplete="off" class="layui-input" lay-verify="required|number">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">图片</label>
			<div class="layui-input-block">
				<span class="layui-btn layui-btn-normal choice_img" style="margin-left: 5px;">选择图片</span>
				<div class="img-list" id="img-list" style="margin-top: 5px;"></div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-col-md6">
				<label class="layui-form-label">音频</label>
				<div class="layui-input-block">
					<span class="layui-btn choice_audio" style="margin-left: 5px;">选择音频</span>
					<div class="audio-list"></div>
					<input type="hidden" name="audio_url" id="audio_url">
					<input type="hidden" name="audio_id" id="audio_id">
				</div>
			</div>
			
			<div class="layui-col-md6">
				<label class="layui-form-label">视频</label>
				<div class="layui-input-block">
					<span class="layui-btn layui-btn-warm choice_video" style="margin-left: 5px;">选择视频</span>
					<div class="video-list"></div>
					<input type="hidden" name="video_url" id="video_url">
					<input type="hidden" name="video_id" id="video_id">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">简介</label>
			<div class="layui-input-block">
				<div id="editor—wrapper">
					<div id="toolbar-container-brief"><!-- 工具栏 --></div>
					<div id="editor-container-brief"><!-- 编辑器 --></div>
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">内容</label>
			<div class="layui-input-block">
				<div id="editor—wrapper">
					<div id="toolbar-container"><!-- 工具栏 --></div>
					<div id="editor-container"><!-- 编辑器 --></div>
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-input-block">
				<button class="layui-btn" lay-submit lay-filter="add">立即提交</button>
			</div>
		</div>
	</form>
</div>
<!--js逻辑-->
<script src="../../lib/layui/layui.js"></script>
<!-- <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script> -->
<script src="../../js/editor/index.js"></script>
<script type="text/javascript">
	layui.use(["form", "okLayer", "okUtils", "okMock", "laydate", 'upload'], function () {
		let $ = layui.jquery;
		let form = layui.form;
		let okMock = layui.okMock;
		var upload = layui.upload;
        let laydate = layui.laydate;
		let okLayer = layui.okLayer;
		let okUtils = layui.okUtils;

		//关闭loading
		okLoading.close();

		const E = window.wangEditor;
		// 创建两个独立的编辑器实例
		const editor = E.createEditor({
			selector: '#editor-container',
		});
		const editorBrief = E.createEditor({
			selector: '#editor-container-brief',
		});
		const toolbarConfig = {}
		//排除指定的菜单,排除图片上传和视频上传
		toolbarConfig.excludeKeys = ['group-image','group-video']
		
		// 分别为每个编辑器创建工具栏
		const toolbar1 = E.createToolbar({
			editor: editor,
			selector: '#toolbar-container',
			config: toolbarConfig,
		});
		const toolbar2 = E.createToolbar({
			editor: editorBrief,
			selector: '#toolbar-container-brief',
			config: toolbarConfig,
		});
		

		//获取url地址中的参数
        var id = okUtils.getUrlParams("id");
		//获取详情
		okUtils.ajax(okMock.api.exhibit_two.detail, "get", {id: id}).done(function (response) {
			if (response.code == HTTP_OK) {
				let one_id = response.data.one_id;
				//将数据填充到表单中
				$('input[name="name"]').val(response.data.name);
				$('input[name="english_name"]').val(response.data.english_name);
				$('input[name="sort"]').val(response.data.sort);
				
				//遍历多媒体文件
				$.each(response.data.item, function (index, item) {
					if (item.type == 1) {
						//把图片展示出来
						$('.img-list').append('<div style="margin: 5px 5px 0 5px;display: inline-block;"><img src="'+ item.url +'" style="height: 200px;"><div class="layui-btn layui-btn-sm layui-btn-danger del_img" data="'+ item.path +'" data-id="'+ item.id +'" style="display: block;margin-top: 2px;">删除</div></div>');	
					} else if (item.type == 2) {
						//把音频展示出来
						$('.audio-list').html('<div style="margin: 5px 5px 0 5px;display: inline-block;"><audio src="'+ item.url +'" controls></audio></div>');
						$('#audio_url').val(item.path);
						$('#audio_id').val(item.id);
					} else if (item.type == 3) {
						//把视频展示出来
						$('.video-list').html('<div style="margin: 5px 5px 0 5px;display: inline-block;"><video style="width:200px;" src="'+ item.url +'" controls></video></div>');
						$('#video_url').val(item.path);
						$('#video_id').val(item.id);
					}
				})
				//图片查看器
				/* layer.photos({
					photos: '#img-list'
					,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
				}); */

				//获取第一级展项数据
				okUtils.ajax(okMock.api.exhibit_one.no_page_list, "get").done(function (response) {
					if (response.code == HTTP_OK) {
						$.each(response.data, function (index, item) {
							if (item.id == one_id) {
								//下拉框赋值
								$('#one_id').append('<option value="' + item.id + '" selected>' + item.name + '</option>');
							} else {
								//下拉框赋值
								$('#one_id').append('<option value="' + item.id + '">' + item.name + '</option>');
							}
						})
						form.render('select');
					} else {
						layer.msg(response.message, { icon: 2, time: 2000 });
					}
				}).fail(function (error) { });

				//将内容填充到编辑器中
				editor.setHtml(response.data.content);
				editorBrief.setHtml(response.data.brief);
				form.render();
			} else {
				layer.msg(response.message, { icon: 2, time: 2000 });
			}
		}).fail(function (error) {});
		

		//上传图片
        var uploadInst = upload.render({
            elem: '.choice_img',
            url: okMock.api.file.upload,
            accept: 'images',   //只允许上传图片类型的文件
            acceptMime: 'image/*',      //（只显示图片类型的文件）
            multiple: true, //支持多文件上传
            headers: {
                'token': okUtils.get_token(),
				'X-CSRF-TOKEN': window.localStorage.getItem('_token'),   //csrf验证
            },
            done: function (res) {
                //如果上传成功
                if (res.code == HTTP_OK) {
                    //上传成功把图片展示出来
                    $('.img-list').append('<div style="margin: 5px 5px 0 5px;display: inline-block;"><img src="'+ res.data.url +'" style="height: 200px;"><div class="layui-btn layui-btn-sm layui-btn-danger del_img" data="'+ res.data.path +'" style="display: block;margin-top: 2px;">删除</div></div>');
                } else {
                    return layer.msg(res.message);
                }
				//图片查看器
				/* layer.photos({
					photos: '#img-list'
					,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
				}); */
            },
            error: function () {}
        });

		//监听删除图片按钮点击事件
        $(document).on('click','.del_img',function () {
            let that = $(this);
            let path = $(this).attr('data');    //获取要删除的图片的路径
            let data_id = $(this).attr('data-id');    //获取要删除的图片的id

			//如果有id说明是之前就有的数据，要把数据表中的数据删除
			if (data_id) {
				okLayer.confirm("数据删除后不可恢复，确定删除吗？", function (index) {
					//删除数据
					okUtils.ajax(okMock.api.exhibit_one.delete_item, "post", {id: data_id,path: path}).done(function (response) {
						if (response.code == HTTP_OK) {
							//删除成功
							that.parent().remove();  //把图片从页面中移除
						} else {
							layer.msg(response.message, { icon: 2, time: 2000 });
						}
					}).fail(function (error) {});
					layer.close(index);
				})
			} else {
				$(this).parent().remove();  //把图片从页面中移除
				//删除文件
				okUtils.ajax(okMock.api.file.delete, "post", {path: path});
			}
        });

		//上传音频
        var uploadInst = upload.render({
            elem: '.choice_audio',
            url: okMock.api.file.upload,
            accept: 'audio',   //只允许上传音频类型的文件
            acceptMime: 'audio/*',      //（只显示音频类型的文件）
            //multiple: true, //支持多文件上传
            headers: {
                'token': okUtils.get_token(),
				'X-CSRF-TOKEN': window.localStorage.getItem('_token'),   //csrf验证
            },
            done: function (res) {
                //如果上传成功
                if (res.code == HTTP_OK) {
                    //上传成功把音频展示出来
                    $('.audio-list').html('<div style="margin: 5px 5px 0 0;display: inline-block;"><audio src="'+ res.data.url +'" controls></audio></div>');

					//删除旧的音频文件,如果已经存在则删除文件
					let audio_url = $('#audio_url').val();
					let audio_id = $('#audio_id').val();
					if (audio_url) {
						if (audio_id) {
							//删除旧的音频文件数据
							okUtils.ajax(okMock.api.exhibit_one.delete_item, "post", {id: audio_id,path: audio_url});
						} else {
							//删除文件
            				okUtils.ajax(okMock.api.file.delete, "post", {path: audio_url});
						}
					}
					$('#audio_url').val(res.data.path);
                } else {
                    return layer.msg(res.message);
                }
            },
            error: function () {}
        });

		//上传视频
        var uploadInst = upload.render({
            elem: '.choice_video',
            url: okMock.api.file.upload,
            accept: 'video',   //只允许上传视频类型的文件
            acceptMime: 'video/*',      //（只显示视频类型的文件）
            headers: {
                'token': okUtils.get_token(),
				'X-CSRF-TOKEN': window.localStorage.getItem('_token'),   //csrf验证
            },
            done: function (res) {
                //如果上传成功
                if (res.code == HTTP_OK) {
                    //上传成功把视频展示出来
                    $('.video-list').html('<div style="margin: 5px 0 0 5px;display: inline-block;"><video style="width: 200px;" src="'+ res.data.url +'" controls></video></div>');

					//删除旧的视频文件,如果已经存在则删除文件
					let video_url = $('#video_url').val();
					let video_id = $('#video_id').val();
					if (video_url) {
						//有id则证明是原来的文件，需要把数据一起删除掉
						if (video_id) {
							//删除旧的视频文件数据
							okUtils.ajax(okMock.api.exhibit_one.delete_item, "post", {id: video_id,path: video_url});
						} else {
							//删除文件
            				okUtils.ajax(okMock.api.file.delete, "post", {path: video_url});
						}
					}
					$('#video_url').val(res.data.path);
                } else {
                    return layer.msg(res.message);
                }
            },
            error: function () {}
        });


		//表单提交
		form.on("submit(add)", function (data) {
			//把编辑器的内容赋值给表单的content字段
			data.field.content = editor.getHtml();
			//把编辑器的内容赋值给表单的brief字段
			data.field.brief = editorBrief.getHtml();

			let img_url = '';
			//获取上传的图片url地址
			$.each($('.del_img'),function () {
				img_url += $(this).attr('data') + ',';
			})
			data.field.img_url = img_url;
			data.field.id = id;

			//发送ajax提交表单数据
			okUtils.ajax(okMock.api.exhibit_two.update, "post", data.field).done(function (response) {
				if (response.code == HTTP_OK) {
                    okLayer.greenTickMsg(response.message, function () {
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    });
                } else {
                    layer.msg(response.message, { icon: 2, time: 2000 });
                }
			}).fail(function (error) {});
			return false;
		});
	})
</script>
</body>
</html>
